package io.renren.modules.course.service.impl;

import io.renren.common.annotation.DataFilter;
import io.renren.common.utils.*;
import io.renren.modules.course.dao.CourseBodyDao;
import io.renren.modules.course.dao.CourseDao;
import io.renren.modules.course.dao.CourseSmallDao;
import io.renren.modules.myCourse.entity.ChooseTestEntity;
import io.renren.modules.sys.entity.SysDeptEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.modules.course.service.*;
import io.renren.modules.course.entity.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service("courseBodyService")
@Transactional
public class CourseBodyServiceImpl extends ServiceImpl<CourseBodyDao, CourseBodyEntity> implements CourseBodyService{

    @Autowired
    CourseBodyDao courseBodyDao;

    @Autowired
    CourseDao courseDao;

    @Autowired
    CourseSmallDao courseSmallDao;


    @Override
    public List<CourseBodyEntity> queryList(Map<String, Object> params){

        return courseBodyDao.getCourseList(params);
    }

    @Override
    public List<CourseBodyEntity> queryListByCourseName(String courseName) {
        return courseBodyDao.queryListByCourseName(courseName);
    }

    @Override
    public List<Long> queryDetpIdList(Long parentId) {
        return baseMapper.queryCourseBodyIdList(parentId);
    }

    @Override
    public List<Long> getSubDeptIdList(Long deptId){
        //部门及子部门ID列表
        List<Long> deptIdList = new ArrayList<>();

        //获取子部门ID
        List<Long> subIdList = queryDetpIdList(deptId);
        getDeptTreeList(subIdList, deptIdList);

        return deptIdList;
    }

    @Override
    public List<TreeEntity> getCourseTree(Integer id) {
        return courseBodyDao.getCourseTree(id);
    }

    @Override
    public List<TreeEntity> getCourseTreeGen(Integer id) {
        return courseBodyDao.getCourseTreeGen(id);
    }

    @Override
    public void uploadTest(Map map) {
        //ReadExcel
        courseBodyDao.uploadTest(map);
    }

    @Override
    public ChooseTestEntity getInfoById(int id) {
        return courseBodyDao.getInfoById(id);
    }

    @Override
    public CourseBodyEntity getCourseBodyById(int id) {
        return courseBodyDao.getCourseBodyById(id);
    }

    @Override
    public int getCourseIdByCourseBodyId(int courseBodyId) {
        return courseBodyDao.getCourseIdByCourseBodyId(courseBodyId);
    }

    @Override
    public void deleteCourseTest(int searching) {
        courseBodyDao.deleteCourseTest(searching);
    }

    @Override
    @Transactional
    public R uploadTests(MultipartFile file) {
        int a=0,b=0,c=0,o=0;
        List<Map> list=new ArrayList<>();
        try {
            ReadExcel readExcel = new ReadExcel();
            List<String[]> data = readExcel.readExcel(file);
            a = data.size()-1;  //行数 除了第一行的行数
            b = data.get(0).length;   //列的数量
            //将数据放入map中存入数据库

			/*Integer chapterId= (Integer) request.getSession().getAttribute("chapterId");
			if(null==chapterId||"-1".equals(chapterId.toString())){
				return 	R.error(101,"请添加章节信息");
			}*/
			/*if(null == request.getSession().getAttribute("courseId") || null == request.getSession().getAttribute("courseBodyId")){
				return 	R.error(101,"请添加章节讲信息");
			}
			int courseId = (Integer) request.getSession().getAttribute("courseId");
			int courseBodyId = (Integer) request.getSession().getAttribute("courseBodyId");*/
            //判断几行
            for( o =0;o<a;o++){
                c=o;
                Map map = new LinkedHashMap();
                map.put("questionTypeId",data.get(o)[0]);
                map.put("questionContent",data.get(o)[1]);
                map.put("questonContentImg",data.get(o)[2]);
                if(null == data.get(o)[3] || "".equals(data.get(o)[3])){
                    return R.error("您的第"+(o+2)+"行没有填写分数哦,请完善后上传");
                }
                map.put("fraction",data.get(o)[3]);
				/*if(null == request.getSession().getAttribute("courseId")||"".equals(request.getSession().getAttribute("courseId"))){
					return R.error(101,"请选择课程后上传");
				}
				map.put("courseId",request.getSession().getAttribute("courseId").toString());    //课程id*/
				/*if( null == request.getSession().getAttribute("courseBodyId")||"".equals(request.getSession().getAttribute("courseBodyId"))){
					return R.error(101,"请选择课程所属章章后上传");
				}*/
                if("".equals(data.get(o)[4])){
                    return R.error("您的第"+(o+2)+"行没有填写所属课程id哦,请完善后上传");
                }
                System.out.println(data.get(o)[4]);
                map.put("courseBodyId",data.get(o)[4]);   //章id
                //获取课程id
                int courseBodyId = Integer.parseInt(data.get(o)[4]);
                int courseId = getCourseIdByCourseBodyId(courseBodyId);
                System.out.println(courseId);
                map.put("courseId",courseId);

                if(null == data.get(o)[6] || "".equals(data.get(o)[6])){
                    map.put("optionOne",null);
                }else{
                    map.put("optionOne",data.get(o)[6]);
                }
                map.put("optionOneImg",data.get(o)[7]);
                map.put("optionTwo",data.get(o)[8]);
                map.put("optionTwoImg",data.get(o)[9]);
                map.put("optionThree",data.get(o)[10]);
                map.put("optionThreeImg",data.get(o)[11]);
                map.put("optionFour",data.get(o)[12]);
                map.put("optionFourImg",data.get(o)[13]);
                map.put("answer",data.get(o)[14]);
                if("".equals(data.get(o)[14]) || null == data.get(o)[14]){
                    return R.error(101,"第"+(o+2)+"行附近未填写答案列表，请完善");
                }
                map.put("analysis",data.get(o)[15]);
                map.put("analysisImg",data.get(o)[16]);
                list.add(map);
            }
            courseBodyDao.insertList(list);
            //修改课程course_body中的question_total数量
            updateQuestionTotal();
            return R.ok("上传成功",100);
        } catch (IOException e) {
            //io流读取异常
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
            return R.error("第"+(o+2)+"行附近数据有问题，请检查");
        }
        return R.error("第"+(o+2)+"行附近数据有问题，请检查");
    }

    @Override
    @Transactional
    public R changeCourseToSmall(MultipartFile file,Long teacherId) {
        int a=0,b=0,c=0,o=0;
        List list=new ArrayList();  // 获取到excel中的需要转的课程的id
        try {
            ReadExcel excel = new ReadExcel();
            List<String[]> data = excel.readExcel(file);
            a = data.size();  //行数 除了第一行的行数

            for(o = 0;o<a;o++){
                CourseSmallEntity courseSmallEntity = new CourseSmallEntity();
                if(null == data.get(o)[0] || "".equals(data.get(o)[0])){
                    return R.error(102,"第"+(o+1)+"行课程未找到，请检查后重新上传");
                }
                int courseBodyId = Integer.valueOf(data.get(o)[0]);   //需要转的课程讲的id
                CourseBodyEntity courseBodyEntity = getCourseBodyById(courseBodyId);   //需要转的课程讲的实体
                if(null == courseBodyEntity){
                    return R.error(102,"第"+(o+1)+"行课程未找到，请检查后重新上传");
                }
                if(null == data.get(o)[1]){
                    return R.error(102,"第"+(o+1)+"行课程未填写简介，请检查后重新上传");
                }
                String courseSmallIntroduce = data.get(o)[1];  // 微课程的简介

                /*if(null != courseBodyEntity.getCourseId()){
                    CourseEntity courseEntity =courseDao.selectById(courseBodyEntity.getCourseId());//讲属于哪个大课
                    //微课所属老师
                    if(null != courseBodyEntity.getCourseId()){
                        if(null != Integer.valueOf(courseEntity.getTalkTeacherId())){
                            courseSmallEntity.setTeacherId(courseEntity.getTalkTeacherId());
                        }
                    }

                }*/

                //微课所属老师
                courseSmallEntity.setTeacherId(Integer.valueOf(teacherId.toString()));

                //微课名称
                if(null != courseBodyEntity.getChapterName()){
                    courseSmallEntity.setTitle(courseBodyEntity.getChapterName());
                }
                //微课图片
                if(null != courseBodyEntity.getDataPath()){
                    if(!"http".equals(courseBodyEntity.getDataPath().substring(0,4))){
                        courseSmallEntity.setPicturePath("http://"+courseBodyEntity.getDataPath());
                    }

                }
                //微课简介
                if(null != courseSmallIntroduce){
                    courseSmallEntity.setIntroduce(courseSmallIntroduce);
                }
                //微课视频地址  优先级：1 video_path  2 video_hd_path
                if(null != courseBodyEntity.getVideoPath()){
                    if(!"http".equals(courseBodyEntity.getVideoPath().substring(0,4))){
                        courseSmallEntity.setVideoPath("http://"+courseBodyEntity.getVideoPath());
                    }

                }
                if(null != courseBodyEntity.getVideoHdPath()){
                    if(!"http".equals(courseBodyEntity.getVideoHdPath().substring(0,4))){
                        courseSmallEntity.setVideoPath("http://"+courseBodyEntity.getVideoHdPath());
                    }

                }
                courseSmallEntity.setType(0);  //微课的类型是0  代表是视频  1代表是音频
                //todo 微课的封面图片
                courseSmallEntity.setCoverPath(" ");
                list.add(courseSmallEntity);
            }

            //创建一个微课程的list
            /*List<CourseSmallEntity> courseSmallEntityList = new ArrayList<>();

            //list是需要转成微课的小讲的id  循环list  获取到将中的信息 存成微课
            for(int x = 0;x<list.size();x++){
                int courseBodyId = Integer.valueOf(list.get(x).toString());
                CourseBodyEntity courseBodyEntity = getCourseBodyById(courseBodyId);
                CourseSmallEntity courseSmallEntity = new CourseSmallEntity();
                if(null != courseBodyEntity.getChapterName()){
                    courseSmallEntity.setTitle(courseBodyEntity.getChapterName());
                }
                if(null != courseBodyEntity.getDataPath()){
                    courseSmallEntity.setPicturePath(courseBodyEntity.getDataPath());
                }
            }*/
            courseSmallDao.changeToSmall(list);
            return R.ok("批量转微课成功",100);
        } catch(Exception e){
            e.printStackTrace();
            return R.error(102,"您的第"+(o+1)+"行数据有问题，请重新上传");
        }
        //return R.ok("批量转微课成功",100);
    }

    /**
     * 修改课程的试题数量
     */
    public void updateQuestionTotal(){
            courseBodyDao.updateQuestionTotal();
    }



    /**
     * 递归
     */
    private void getDeptTreeList(List<Long> subIdList, List<Long> deptIdList){
        for(Long deptId : subIdList){
            List<Long> list = queryDetpIdList(deptId);
            if(list.size() > 0){
                getDeptTreeList(list, deptIdList);
            }

            deptIdList.add(deptId);
        }
    }
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<CourseBodyEntity> page = this.selectPage(
                new Query<CourseBodyEntity>(params).getPage(),
                new EntityWrapper<CourseBodyEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<TreeEntity> courseBodyService() {
        List<TreeEntity> list=new  ArrayList();

        return list;
    }

}
